<template>
    <view class="MaterialModal" v-if="visible">
        <!-- 弹窗遮罩层，点击关闭弹窗 -->
        <view class="modal-overlay"></view>
        <view class="modal-content">
            <!-- 弹窗头部标题 -->
            <view class="modal-header">
                <view class="title">素材模版</view>
            </view>
            <!-- 使用原生 picker 实现下拉菜单 -->
            <view class="dropdown-menu">
                <picker
                        mode="multiSelector"
                        :range="dropdownOptions"
                        @change="onPickerChange"
                        @columnchange="onColumnChange">
                    <view class="dropdown-item">
                        {{ selectedPrimaryLabel || '请选择' }} - {{ selectedSecondaryLabel || '请选择' }}
                    </view>
                </picker>
            </view>
            <!-- 图片列表，支持滚动 -->
            <scroll-view
                         class="image-list"
                         scroll-y
                         @scroll="onScroll">
                <view
                      v-for="(img, index) in filteredImages"
                      :key="index"
                      :class="['image-item', { selected: selectedImageIndex === index }]"
                      @touchstart="selectImage(index)">
                    <image :src="img" class="image" mode="aspectFill" />
                </view>
                <!-- 到底提示 -->
                <view v-if="!materialStore.hasNext" class="end-text">--到底了--</view>
            </scroll-view>
            <!-- 底部按钮 -->
            <view class="modal-footer">
                <button class="cancel-btn" @click="closeModal">取消</button>
                <button class="confirm-btn" @click="onConfirm">确定</button>
            </view>
        </view>
    </view>
</template>

<script>
import { autorun, toJS } from "mobx"; // 监听数据变化
import materialStore from "./materialStore";
import utils from "src/utils";
import designEditorRender from "../../DesignEditor/designEditorRender";
import imgCache from "../../myFabric/imgCache";

export default {
    name: "MaterialModal",
    props: {
    },
    data() {
        return {
            visible: false, // 是否显示弹窗
            tabs: ["素材模版", "我的图片", "收藏图片"], // 切换菜单选项
            activeTab: 0, // 当前激活的选项索引
            dropdownOptions: [[], []], // 二级下拉菜单选项
            selectedPrimaryLabel: "", // 当前选中的一级菜单 label
            selectedSecondaryLabel: "", // 当前选中的二级菜单 label
            data: [],
            stickers: [], // 图片
            selectedImageIndex: null, // 当前选中的图片索引
            localImages: [] // 本地图片列表
        };
    },
    computed: {
        filteredImages() {
            // 根据选中的分类返回不同的图片列表
            return this.localImages; // 使用本地图片列表
        }
    },
    watch: {
    },
    methods: {
        // 切换菜单
        switchTab(index) {
            this.activeTab = index;
        },
        // picker 选择事件
        onPickerChange(event) {
            const [primaryIndex, secondaryIndex] = event.detail.value;
            console.log('event.detail', primaryIndex, secondaryIndex, toJS(materialStore.cascaderOptions));
            const primaryOption = this.dropdownOptions[0][primaryIndex];
            const secondaryOption = this.dropdownOptions[1][secondaryIndex];

            if (primaryOption && secondaryOption) {
                this.selectedPrimaryLabel = primaryOption;
                this.selectedSecondaryLabel = secondaryOption;
                console.log("选中的一级分类:", primaryOption);
                console.log("选中的二级分类:", secondaryOption);
            }

            const cascaderOptions = toJS(materialStore.cascaderOptions);
            const primary = cascaderOptions[primaryIndex];
            const secondary = primary?.children?.[secondaryIndex];
            //调研 materialStore.setActiveid 方法
            materialStore.setActiveid([primary.value, secondary.value]);
        },
        // 列切换事件
        onColumnChange(event) {
            const { column, value } = event.detail;
            if (column === 0) {
                // 更新二级菜单选项
                const selectedPrimary = this.data[value];
                this.dropdownOptions[1] = selectedPrimary?.children?.map(option => option.text) || [];
                this.selectedSecondaryLabel = this.dropdownOptions[1][0] || "请选择";
                console.log("更新的二级菜单:", this.dropdownOptions[1]);
            }
        },
        // 初始化下拉菜单数据
        initDropdownOptions() {
            if (this.data.length > 0) {
                this.dropdownOptions = [
                    this.data.map(option => option.text),
                    this.data[0]?.children?.map(option => option.text) || []
                ];
                this.selectedPrimaryLabel = this.dropdownOptions[0][0] || "请选择";
                this.selectedSecondaryLabel = this.dropdownOptions[1][0] || "请选择";
            } else {
                this.dropdownOptions = [[], []]; // 确保下拉菜单有默认值
            }
        },
        closeModal() {
            materialStore.setVisible(false);
        },
        // 滚动到底部时触发
        onScrollToLower() {
            // console.log('滚动到底部事件触发');
            // materialStore.getNextPage();
        },
        // 滚动事件，检查距离底部的距离
        onScroll(event) {
            const { scrollHeight, scrollTop } = event.detail;
            const viewHeight = Taro.getWindowInfo().windowHeight - 300; // 与 scroll-view 的高度一致
            if (scrollHeight - scrollTop - viewHeight < 100) {
                materialStore.getNextPage();
            }
        },
        // 选中图片
        async selectImage(index) {
            this.selectedImageIndex = index;
            await designEditorRender.preloadImg(utils.ossSuffix(this.localImages[this.selectedImageIndex], 512));
        },
        // 确定按钮点击事件
        onConfirm() {
            //把当前选中的图片地址传给
            const src = this.localImages[this.selectedImageIndex];
            if (src) {
                designEditorRender.addImg(utils.ossSuffix(src, 512));
                materialStore.setVisible(false);
            }
        }
    },
    mounted() {
        this.dispose = autorun(() => {
            this.data = toJS(materialStore.cascaderOptions); // 监听图片列表变化
            this.initDropdownOptions(); // 初始化下拉菜单
        });
        this.dispose2 = autorun(() => {
            const image = toJS(materialStore.stickers); // 监听图片列表变化
            this.localImages = image.map(item => utils.ossSuffix(item.url, 200));
        });
        this.dispose3 = autorun(() => {
            this.visible = materialStore.visible; // 监听弹窗显示状态
        });
    },
    destroyed() {
        this.dispose(); // 销毁监听器
        this.dispose2();
    }
};
</script>

<style scoped lang="scss">
.MaterialModal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;

    .modal-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5); // 半透明背景
    }

    .modal-content {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%); // 居中显示
        width: 80%;
        background: #ffffff;
        border-radius: 8px;
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .modal-header {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 12px;
            background: #f5f5f5;
            border-bottom: 1px solid #e6e6e6;

            .title {
                font-size: 16px;
                font-weight: bold;
                color: #333333;
            }
        }

        .dropdown-menu {
            padding: 8px 12px;
            background: #f9f9f9;
            border-bottom: 1px solid #e6e6e6;

            .dropdown-item {
                text-align: center;
                padding: 8px;
                background: #ffffff;
                border: 1px solid #cccccc;
                border-radius: 4px;
                font-size: 14px;
                color: #333333;
            }
        }

        .image-list {
            padding: 12px;
            width: 100%;
            box-sizing: border-box;
            height: calc(100vh - 300px);
            overflow-y: auto;
            display: block;

            .image-item {
                display: inline-block;
                width: 50%;
                height: 120px;
                text-align: center;
                margin: 5px 0px;
                border-radius: 4px;
                border: 2px solid #ffffff;
                box-sizing: border-box;


                &.selected {
                    border-color: #FF5E10; // 红色边框
                }

                .image {
                    width: 100%;
                    height: 100%;
                    border-radius: 4px;
                }
            }

            .end-text {
                width: 100%;
                text-align: center;
                font-size: 14px;
                color: #999999;
                margin-top: 10px;
            }
        }

        .modal-footer {
            display: flex;
            justify-content: space-between;
            padding: 12px;
            background: #f5f5f5;
            border-top: 1px solid #e6e6e6;

            .cancel-btn {
                flex: 1;
                margin-right: 8px;
                padding: 2px 8px;
                background: #ffffff;
                border: 1px solid #cccccc;
                border-radius: 4px;
                font-size: 14px;
                color: #333333;
                text-align: center;
            }

            .confirm-btn {
                flex: 1;
                margin-left: 8px;
                padding: 2px 8px;
                background: #FF5E10;
                border: none;
                border-radius: 4px;
                font-size: 14px;
                color: #ffffff;
                text-align: center;
            }
        }
    }
}
</style>
